#include <stdio.h>
#include <stdint.h>

uint8_t calculate_checksum(uint8_t *data, size_t length) {
    uint32_t checksum = 0;  // 使用32位整数来避免溢出
    for (size_t i = 0; i < length - 2; i++) {
        checksum += data[i];
    }
    return checksum % 256;  // 取低8位
}

uint8_t bytes[64] = {0};
void hex_str_to_bytes(const char* input) {
    // 创建可修改的字符串副本
    char* str = strdup(input);
    char* token;
    int count = 0;

    // 分割字符串
    token = strtok(str, " ");
    while (token != NULL && count < 64) {
        // 将十六进制字符串转换为字节
        bytes[count++] = (uint8_t)strtoul(token, NULL, 16);
        token = strtok(NULL, " ");
    }

    free(str);

    // 打印结果
    printf("uint8_t data[] = {");
    for (int i = 0; i < count; i++) {
        printf("0x%02X", bytes[i]);
        if (i < count - 1) printf(", ");
    }
    printf("};\n");
}

int main() {
    const char* input = "AA 0B 20 81 03 00 00 02 76 0A 00 00 00 DB 2F  ";
    hex_str_to_bytes(input);
    // uint8_t data[] =bytes;

    // // uint8_t data[] = {0xAA, 0x0B, 0x20, 0x81, 0x03, 0x00, 0x00, 0x01, 0xC2, 0x0A, 0x00, 0x00, 0x00, 0x26, 0x2F};
    // //                 //、AA 0B 20 81 03 00 00 01 C2 0A 00 00 00 26 2F 
    // size_t length = sizeof(data) / sizeof(data[0]);
    // uint8_t checksum = calculate_checksum(data, length);
    // printf("Checksum: 0x%02X\n", checksum);

    size_t length = sizeof(bytes) / sizeof(bytes[0]);
    uint8_t checksum = calculate_checksum(bytes, length);
    printf("Checksum: 0x%02X\n", checksum);
    printf("length: %d\n", length);



    return 0;
}
